# gozerbot/config.py
#
#

""" this is where the config dict lives """

__copyright__ = 'this file is in the public domain'

import os, pickle, popen2
from gozerbot.datadir import datadir

# version strings
ver = 'PYJBOT 0.3'

def gethgrev():
    """ get mercurial revision """
    rev = None
    try:
        proces = popen2.Popen4('hg tip')
        data = proces.fromchild.readlines()
        if not proces.wait():
            rev = int(data[0].split(':')[1].strip())
    except Exception, ex:
        pass
    return rev

def getsvnrev():
    """ get subversion revision """
    rev = None
    try:
        proces = popen2.Popen4('svn info')
        data = proces.fromchild.readlines()
        if not proces.wait():
            for i in data:
                if i.startswith('Revision'):
                    rev = i.split()[1]
    except Exception, ex:
        pass
    return rev

def diffdict(dictfrom, dictto):
    """ check for differences between two dicts """
    temp = {}
    for i in dictto.iteritems():
        if dictfrom.has_key(i[0]):
            if dictfrom[i[0]] != i[1]:
                temp.setdefault(i[0], i[1])
        else:
            temp.setdefault(i[0], i[1])
    return temp

class Config(dict):

    """ config object is a dict """

    def __init__(self, datadir, *args, **kw):
        dict.__init__(self, *args, **kw)
        self.datadir = str(datadir)

    def __getitem__(self, item):
        if not self.has_key(item):
            return None
        else:
            return dict.__getitem__(self, item)

    def set(self, item, value):
        """ set a config item """
        dict.__setitem__(self, item, value)
        self.save()

    def load(self):
        """ load the config file """
        frompickle = {}
        picklemodtime = None
        # first do reload of the data/config file
        self.reload()
        # see if there is a configpickle
        try:
            picklemodtime = os.stat(self.datadir + '/configpickle')[8]
            configpickle = open(self.datadir + '/configpickle', 'r')
            frompickle = pickle.load(configpickle)
            configpickle.close()
        except:
            pass
        # see if data/config is more recent than the configpickle
        configmodtime = os.stat(self.datadir + '/config')[8]
        if picklemodtime and picklemodtime > configmodtime:
            # if so update the config dict with the pickled data
            a = diffdict(self, frompickle)
            self.update(a)
        # set version
        if self['dbenable']:
            self['version'] = ver + ' DATABASE'
        else:
            self['version'] = ver
        rev = gethgrev()
        if rev:
            self['version'] += " HG revision %s" % rev
            return
        rev = getsvnrev()
        if rev:
            self['version'] += " SVN revision %s" % rev
    
    def save(self):
        """ save config data to pickled file """
        picklefile = open(self.datadir + '/configpickle', 'w')
        pickle.dump(self, picklefile)
        picklefile.close()

    def reload(self):
        """ use execfile to reload data/config """
        execfile(self.datadir + '/config', config)
        # remove builtin data
        del self['__builtins__']
        # set version
        if self['dbenable']:
            self['version'] = ver + ' DATABASE'
        else:
            self['version'] = ver
        rev = gethgrev()
        if rev:
            self['version'] += " HG revision %s" % rev
            return
        rev = getsvnrev()
        if rev:
            self['version'] += " SVN revision %s" % rev

# create the config dict and load it from file
config = Config(datadir)
config.load()
